package com.uh.rds.testing.validator.types;

import com.uh.rds.testing.validator.DataValidatorBase;

import java.util.*;

public class StringDataValidator  extends DataValidatorBase {
    //private Map<String, String> stringData;

    @Override
    public String getType() {
        return "String";
    }

//    @Override
//    public void init(Integer index, DataTesterConfig config, Map<String, List<String[]>> orgData) {
//
//        this.index = index;
//        this.validSize = 0;
//        this.config = config;
//        this.size = orgData.size();
//        this.procSize = this.size;
//        reverseKeys(orgData, config);
//        initStepSize();
//
//        // orgData 转换为 stringData 的 key-value 形式
//        this.stringData = new HashMap<>(orgData.size());
//        for(Map.Entry<String, List<String[]>> entry : orgData.entrySet()) {
//            String key = entry.getKey();
//            for(String[] value : entry.getValue()) {
//                stringData.put(key, value[0]);
//                break;
//            }
//        }
//
//        logger.info("{} Validator was created! Data size:{}", getName(), stringData.size());
//    }



    @Override
    public void process() {

        if(processJedis.isConnected() == false)  processJedis.connect();

        processBeginLog();

        for(Map.Entry<String, List<String[]>> entry : data.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue().get(0)[0]; // 只取第一个值
            String ret = processJedis.set(key, value);
            boolean succeed = ret != null && ret.equals("OK");
            processingLog(succeed);
        }

        processEndLog();
    }

    @Override
    public long expire(int expireSeconds) {
        return super.expire(processJedis, data.keySet(), expireSeconds);
    }

    @Override
    public boolean validateExpired() {
        return super.validateExpired(validateJedis, data.keySet());
    }


    @Override
    public boolean validate() {
        if(!validateJedis.isConnected())  validateJedis.connect();

        validateBeginLog();

        Collection<String> keys = arguments.isValidateReversed() ? reversedKeys : data.keySet();
        for(String key : keys) {
            boolean keyMatched = true;
            String value = validateJedis.get(key);
            String expectedValue = data.get(key).get(0)[0];
            if(value == null || !value.equals(expectedValue)) {
                keyMatched = false;
                logger.error("{} validate failed! key[{}] expected value:{} actual value:{}",
                        getName() , key, expectedValue, value);
            }

            validatingLog(keyMatched);
        }

        return validateEndLog();
    }

    @Override
    public long clear() {
        return clear(processJedis, validateJedis, data.keySet());
    }

}
